<template>
  <div class="commodity-form">
    <!-- 表单 -->
    <a-form-model
      ref="ruleForm"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 19 }">
      <a-form-model-item prop="appId">
        <template slot="label">
          <span style="color: red">*</span>直播平台
        </template>
        <a-radio-group
          :disabled="checkDisable('appId')"
          v-model="formData.appId"
          @change="changeAPPID">
          <a-radio v-for="(item, index) in liveAppIdList" :key="index" :value="item.value" :disabled="(userInfo.shopRoleCode != 'role:store:main') && (item.value == '100000054')">{{ item.label }}</a-radio>
          <a-radio :value="'3'" :disabled="userInfo.shopRoleCode != 'role:store:main'">其他小程序</a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item prop="goodsId" v-if="formData.appId == '100000054'">
        <template slot="label">
          <span style="color: red">*</span>添加商品
        </template>
        <a-button :disabled="checkDisable('goodsId')" type="primary" @click="selectGoods">{{ formData.goodsId ? '重新选择商品' : '选择商品' }}</a-button>
      </a-form-model-item>
      <a-form-model-item prop="goodsId" v-if="formData.appId == '100000055'">
        <template slot="label">
          <span style="color: red">*</span>添加商品
        </template>
        <a-button :disabled="checkDisable('goodsId')" type="primary" @click="selectShopGoods">{{ formData.goodsId ? '重新选择商品' : '选择商品' }}</a-button>
      </a-form-model-item>
      <template v-if="formData.appId == '3'">
        <a-form-model-item prop="goodsId">
          <template slot="label">
            <span style="color: red">*</span>APPID
          </template>
          <a-input allow-clear
            style="width:415px"
            v-model="formData.name"
            :disabled="checkDisable('goodsId')"
            placeholder="输入其他小程序APPID" />
        </a-form-model-item>
      </template>
      <a-form-model-item prop="name">
        <template slot="label">
          <span style="color: red">*</span>商品名称
        </template>
        <a-input allow-clear
          style="width:415px"
          v-model="formData.name"
          :disabled="checkDisable('name')"
          :maxLength="14"
          placeholder="输入商品名称，限6-14字" />
      </a-form-model-item>
      <a-form-model-item v-if="showPrice()" label="商品原价" prop="goodPrice">
        {{ formData.goodPriceStr+'元' }}
      </a-form-model-item>
      <a-form-model-item prop="coverImgLocal">
        <template slot="label">
          <span style="color: red">*</span>商品封面
        </template>
        <div class="upload-box">
          <upload-image class="img"
            :uploadUrl="'/upload'"
            :disabled="checkDisable('coverImgLocal')"
            :fileSizeLimit="1048576"
            v-model="formData.coverImgLocal"
            :afterUploadFun="afterUploadFun"></upload-image>
          <div class="upload-txt">
            建议尺寸：200像素 * 200像素，<br>
            图片大小不得超过1M的。
          </div>
        </div>
      </a-form-model-item>
      <a-form-model-item prop="url">
        <template slot="label">
          <span style="color: red">*</span>商品链接
        </template>
        <a-textarea
          placeholder="输入商品链接"
          style="width:415px"
          :disabled="checkDisable('url')"
          v-model="formData.url"
          :rows="4" />
      </a-form-model-item>
      <a-form-model-item prop="priceType">
        <template slot="label">
          <span style="color: red">*</span>价格形式
        </template>
        <div class="price-box">
          <div class="price-item">
            <a-radio-group
              :disabled="checkDisable('priceType')"
              v-model="formData.priceType"
              @change="selectPriceType">
              <a-radio :value="1" class="slt-item">一口价</a-radio>
              <a-radio :value="2" class="slt-item">价格区间</a-radio>
              <a-radio :value="3" class="slt-item">显示折扣价</a-radio>
            </a-radio-group>
          </div>
          <div class="price-input">
            <div class="slt-item">
              <template v-if="formData.priceType == 1">
                <span class="txt">价格</span>
                <a-input-number :min="0" :max="formData.goodPrice" :disabled="checkDisable('setPrice')" v-model="formData.setPrice" /> 元
              </template>
            </div>
            <div class="slt-item">
              <template v-if="formData.priceType == 2">
                <span class="txt">价格</span>
                <a-input-number :min="0" :max="formData.goodPrice" :disabled="checkDisable('setPrice')" v-model="formData.setPrice"/> 元 —
                <a-input-number :min="0" :max="formData.goodPrice" :disabled="checkDisable('setPrice2')" v-model="formData.setPrice2"/> 元
              </template>
            </div>
            <div class="slt-item">
              <template v-if="formData.priceType == 3">
                <span class="txt">市场价</span><a-input-number :min="0" :max="formData.goodPrice" :disabled="checkDisable('setPrice')" v-model="formData.setPrice" /> 元
                <span class="txt">现价</span><a-input-number :min="0" :max="formData.goodPrice" :disabled="checkDisable('setPrice2')" v-model="formData.setPrice2" /> 元
              </template>
            </div>
          </div>
        </div>
      </a-form-model-item>
      <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
        <a-col :offset="2">
          <a-space>
            <a-button v-if="handle != 'view' && (!formData.auditStatus || formData.auditStatus == 0)" :loading="confirmLoading" class="btn" key="submit" type="primary" @click="handleSubmit('1')"> 保存商品 </a-button>
            <a-button v-if="handle != 'view'" :loading="confirmLoading" class="btn" key="check" type="primary" @click="handleSubmit('2')"> 提交并审核 </a-button>
            <a-button class="btn" key="back" @click="closeModal"> {{ handle == 'view' ? '返回' : '取消' }} </a-button>
          </a-space>
        </a-col>
      </a-form-model-item>
    </a-form-model>
    <!-- 选择商品 -->
    <select-commodity ref="selectCommodity" :goodsId="formData.goodsId" :hasChosenGoodsIds="hasChosenGoodsIds" @chooseGoods="chooseGoods"></select-commodity>
    <select-shop-commodity ref="selectShopCommodity" :goodsId="formData.goodsId" :hasChosenGoodsIds="hasChosenGoodsIds" @chooseGoods="chooseGoods"></select-shop-commodity>
  </div>
</template>

<script>
  import { mapGetters } from "vuex";
  import deepCopy from '@/utils/deepCopy'
  import selectCommodity from './../components/selectCommodity.vue';
  import selectShopCommodity from './../components/selectShopCommodity.vue';
  import { createOptionsByDict } from '@/utils/dict'
  const formData={
    appId: undefined, // 平台编号
    goodsId: undefined, // 商品ID
    name: undefined, // 商品名称
    coverImgLocal: undefined, // 商品封面
    coverImgUrl: undefined, // 商品封面mediaId
    url: undefined, // 商品链接
    goodPrice: 0, // 商品原价
    goodPriceStr: 0, // 商品原价(字符串)
    priceType: 1, // 价格形势
    setPrice: 0, // 一口价\左边界\原价
    price: 0,
    setPrice2: 0, // 右边界\现价
    price2: 0,
    goodsInventoryTotal: 0, // 商品库存
    productStatus: undefined, // 商品提交审核状态
    auditStatus: undefined, // 微信审核状态
    remark: undefined, // 是否提交微信审核
  }
  export default {
    name: "MarketingLiveCommodityPagesCommodityForm",
    components: {
      selectCommodity,
      selectShopCommodity
    },
    computed: {
      ...mapGetters(["userInfo"]),
      // 操作类型
      handle() {
        return this.$route.query.handle || "";
      },
      // 直播平台
      appId() {
        return this.$route.query.appId || "";
      },
      // 所属店铺
      blong() {
        return this.$route.query.blong || "";
      },
      // 直播商品id
      id() {
        return this.$route.query.id || "";
      },
    },
    data() {
      return {
        liveAppIdList: createOptionsByDict('LIVE_APPID'), // 直播平台
        headParams: { baseURL: '/goldenhome/gh/live/admin' }, // 接口域名
        uploadUrl: '/product/uploadImage', // 上传接口
        formData,
        rules: {},
        confirmLoading: false, // 防连点
        resetChooseGoods: false, // 编辑时重新选择了商品
        hasChosenGoodsIds: [], // 所有已被选择添加到商品库的商品id集合
      }
    },
    created() {
      this.resetData()
      if(this.id){
        this.getLiveGoodsInfo(this.id)
      }
      this.getAllChosenGoodsIds()
    },
    methods: {
      // 获取所有添加商品id集合
      getAllChosenGoodsIds() {
        let _this = this
        this.$get('/product/pageForJPIds',
          {
            appId: _this.formData.appId
          },
          { baseURL: `${location.origin}/goldenhome/gh/live/admin` })
        .then(res => {
          if(res && res.returnCode=='1000'){
            this.hasChosenGoodsIds = res.dataInfo
          }
        })
      },
      //重置
      resetData(){
        this.formData=deepCopy(formData);
        if(this.appId) {
          this.formData.appId=this.appId
        } else {
          if(this.$store.state.userInfo.shopRoleCode == 'role:store:main') {
            this.formData.appId=createOptionsByDict('LIVE_APPID')[0] ? createOptionsByDict('LIVE_APPID')[0].value : '100000054'
          } else if(this.$store.state.userInfo.shopRoleCode == 'role:store:branch') {
            this.formData.appId=createOptionsByDict('LIVE_APPID')[1] ? createOptionsByDict('LIVE_APPID')[1].value : '100000055'
          }
        }
      },
      // 切换商品来源
      changeAPPID(val) {
        this.formData.goodsId = undefined
        this.formData.name = undefined
        this.formData.coverImgLocal = undefined
        this.formData.coverImgUrl = undefined
        this.formData.url = undefined
        this.formData.goodPrice = 0
        this.formData.goodPriceStr = 0
        this.formData.goodsInventoryTotal = 0
      },
      // 获取直播商品信息
      async getLiveGoodsInfo(id) {
        let _this = this
        let res = await this.$post('/product/query',
          {
            appId: _this.formData.appId,
            goodsId: id
          },
          { baseURL: `${location.origin}/goldenhome/gh/live/admin` });
        if(res && res.returnCode=='1000'){
          if(res.dataInfo){
            res.dataInfo.setPrice = typeof res.dataInfo.price == 'string' ? Number((Number(res.dataInfo.price)/100).toFixed(2)) : Number((res.dataInfo.price/100).toFixed(2))
            res.dataInfo.setPrice2 = typeof res.dataInfo.price2 == 'string' ? Number((Number(res.dataInfo.price2)/100).toFixed(2)) : Number((res.dataInfo.price2/100).toFixed(2))
            this.formData = deepCopy(res.dataInfo)
          }
        }
      },
      // 表单可编辑
      checkDisable(key) {
        let res = false
        if(this.handle == 'view') {
          res = true
        } else if(this.handle == 'edit') {
          let keys = [ 'appId', 'goodsId', 'name', 'coverImgLocal', 'url' ]
          if(this.formData.auditStatus == '2' && keys.includes(key)) {
            res = true
          } else {
            if(key != 'appId') {
              res = false
            } else {
              res = true
            }
          }
        }
        return res
      },
      // 选择商品
      selectGoods() {
        this.$refs.selectCommodity.formVisible = true;
      },
      selectShopGoods() {
        this.$refs.selectShopCommodity.formVisible = true;
      },
      // 选择完商品
      chooseGoods(data) {
        let _this = this
        if(data.commodityType == '1'){
          this.formData.goodsId = data.id
          this.resetChooseGoods = true
          this.formData.name = data.goodsName
          this.formData.goodsInventoryTotal = data.goodsInventoryTotal
          this.formData.goodPrice = Number((typeof data.salePrice == 'string') ? (Number(data.salePrice)/100).toFixed(2) : (data.salePrice/100).toFixed(2))
          let goodPrice = Number((typeof data.salePrice == 'string') ? (Number(data.salePrice)/100).toFixed(2).toString() : (data.salePrice/100).toFixed(2)).toString()
          let rs = goodPrice.indexOf('.')
          if(rs < 0) {
            rs = goodPrice.length;
            goodPrice += '.';
          } while (goodPrice.length <= rs + 2) {
            goodPrice += '0';
          }
          this.formData.goodPriceStr = goodPrice
        }
        let filename = new Date().valueOf().toString()+'.'+data.goodsPicture.substring(data.goodsPicture.lastIndexOf('.') + 1);
        let image = new Image()
        image.src = data.goodsPicture
        image.setAttribute("crossOrigin", "Anonymous")
        image.onload = function() {
          // if(data.goodsPicture.substring(data.goodsPicture.lastIndexOf('.') + 1) != 'jpg' && data.goodsPicture.substring(data.goodsPicture.lastIndexOf('.') + 1) != 'jpeg') {
          //   _this.$refs.selectCommodity.formVisible = false;
          //   _this.$message.error('图片仅支持1M以内的jpg/jpeg格式，请重新上传图片');
          // } else {
            if(image.width > 200 || image.height > 200) {
              _this.$confirm({
                title: '确认操作',
                content: '图片宽高不符合规范，继续上传可能会导致图片变形，是否继续？',
                okText: '继续上传',
                cancelText: '重新上传',
                onOk() {
                  let file = _this.imgToFile(image, filename)
                  _this.fileUpload(file, true)
                },
                onCancel() {},
              });
            } else {
              let file = _this.imgToFile(image, filename)
              _this.fileUpload(file, true)
            }
          }
        // }
        if(this.formData.appId == '100000054') {
          this.formData.url = 'pagesA/shop/goodsDetail?id='+data.id
          this.$refs.selectCommodity.formVisible = false;
        } else if(this.formData.appId == '100000055') {
          if(data.commodityType == '1') {
            this.formData.url = 'pagesA/shop/goodsDetail?id='+data.id
          }
          this.$refs.selectShopCommodity.formVisible = false;
        }
      },
      // 判断 图片是否符合
      // 是否显示原价
      showPrice() {
        let res = false
        if(this.handle == 'add'){
          res = true
        } else {
          if(this.resetChooseGoods){
            res = true
          }
        }
        return res
      },
      // 上传图片
      fileUpload(file, bool) {
        this.$upload(this.uploadUrl,
          file,
          {
            ...this.headParams,
            params: {appId: this.formData.appId}
          }).then(res => {
          if(bool){
            this.getImgUrl(file)
          }
          if(res.dataInfo.imageDataInfo){
            this.formData.coverImgLocal = res.dataInfo.imageDataInfo.url
          }
          this.formData.coverImgUrl = res.dataInfo.mediaId
        })
      },
      // 图片转base64，再转文件流，上传图片
      imgToFile(img, filename) {
        // 图片转base64
        let canvas = document.createElement("canvas")
        canvas.width = 200
        canvas.height = 200
        let ctx = canvas.getContext("2d")
        ctx.drawImage(img, 0, 0, 200, 200)
        let ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase()
        let dataURL = canvas.toDataURL("image/" + ext)
        // base转文件流
        let arr = dataURL.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, { type: mime });
      },
      // 上传完图片处理数据
      afterUploadFun(data) {
        let filename = new Date().valueOf().toString()+'.'+data.url.substring(data.url.lastIndexOf('.') + 1);
        console.log(filename)
        let _this = this
        let image = new Image()
        image.src = data.url
        image.setAttribute("crossOrigin", "Anonymous")
        image.onload = function() {
          if(image.width > 200 || image.height > 200) {
            _this.$message.error('图片宽高不符合规范，请重新上传！');
            return
          } else {
            let file = _this.imgToFile(image, filename)
            _this.fileUpload(file)
            setTimeout(() => {
              _this.formData.coverImgLocal = data.url
            },100)
          }
        }
      },
      // 调用金牌上传图片方法
      getImgUrl(file) {
        this.$upload('/upload',
          file,
          {})
        .then(res => {
          if (res && res.returnCode === 1000) {
            this.formData.coverImgLocal = res.dataInfo.url
          }
        })
      },
      // 获取商品链接
      async getGoodsUrl(id) {
        let _this = this
        let res = await this.$post('/product/queryWxProduct',
          {
            appId: _this.formData.appId,
            goodsIds: [id]
          },
          { baseURL: `${location.origin}/goldenhome/gh/live/admin` });
        if(res && res.returnCode=='1000'){
          this.formData.url = res.dataInfo.goods[0].url
        } else {
          this.$message.error('请重新选择商品！');
        }
      },
      // 选择价格类型
      selectPriceType(e) {
        if(e.target.value != 3) {
          this.formData.setPrice = 0;
        } else {
          this.formData.setPrice = this.formData.goodPrice || 0;
        }
        this.formData.setPrice2 = 0;
      },
      // 返回列表页
      closeModal() {
        this.confirmLoading = false
        // this.$router.back();
        this.$router.push({
          name:'MarketingLiveCommodity',
          query: {
            current:this.$route.query.current||1,
            blong: this.$route.query.blong,
            appId:this.$route.query.appId||this.formData.appId
          }
        })
      },
      // 提交表单
      handleSubmit(type) {
        // 验证是否选择商品
        if(!this.formData.goodsId) {
          return this.$message.error('请选择商品');
        }
        // 验证商品名称
        if(!this.formData.name) {
          return this.$message.error('请输入商品名称');
        } else {
          if(this.formData.name.length < 6 || this.formData.name.length > 14){
            return this.$message.error('商品名称为6-14字');
          }
        }
        // 验证商品封面
        if(!this.formData.coverImgLocal) {
          return this.$message.error('请上传商品封面');
        }
        // 验证商品链接
        if(!this.formData.url) {
          return this.$message.error('请输入商品链接');
        }
        // 验证商品价格形式
        if(!this.formData.priceType) {
          return this.$message.error('请选择价格形式');
        }
        // 验证一口价
        if(this.formData.priceType == 1) {
          if(!this.formData.setPrice) {
            return this.$message.error('请输入一口价');
          }
        }
        // 验证价格区间
        if(this.formData.priceType == 2) {
          if(!this.formData.setPrice) {
            return this.$message.error('请输入最低价格');
          }
          if(!this.formData.setPrice2) {
            return this.$message.error('请输入最高价格');
          }
          if(this.formData.setPrice2<=this.formData.setPrice){
            return this.$message.error('最高价格不能小于等于最低价格');
          }
        }
        // 验证折扣价
        if(this.formData.priceType == 3) {
          if(!this.formData.setPrice) {
            return this.$message.error('请输入市场价');
          }
          if(!this.formData.setPrice2) {
            return this.$message.error('请输入现价');
          }
        }
        if(this.formData.setPrice) {
          this.formData.price = Math.round(this.formData.setPrice * 10 * 10)
        }
        if(this.formData.setPrice2) {
          this.formData.price2 = Math.round(this.formData.setPrice2 * 10 * 10)
        }
        let url = ''
        switch (this.handle) {
          case 'add':
            if(type == 1) {
              url = '/product/add'
            } else if(type == 2) {
              url = '/product/addProduct'
            }
            break;
          case 'edit':
            if(this.formData.remark != 1) {
              if(type == 1) {
                url = '/product/update'
              } else if(type == 2) {
                url = '/product/addProduct'
              }
            } else {
              if(this.formData.productStatus == 2){
                if(type == 1) {
                  url = '/product/update'
                } else if(type == 2) {
                  url = '/product/retryaudit'
                }
              } else {
                url = '/product/updateProduct'
              }
            }
            break;
        }
        this.confirmLoading = true
        this.$post(url,
          this.formData,
          { baseURL: `${location.origin}/goldenhome/gh/live/admin` })
        .then(res => {
          if(res && res.returnCode=='1000'){
            this.confirmLoading = false
            this.closeModal()
            return this.$message.success('操作成功！');
          } else {
            this.confirmLoading = false
            return this.$message.error('操作失败！');
          }
        })
        .catch(err => {
          this.confirmLoading = false
        })
      },
    }
  }
</script>

<style scoped lang="less">
.commodity-form{
  .price-box{
    display: flex;
    // .price-item{}
    .price-input{
      padding-left: 8px;
      .txt{
        display: inline-block;
        width: 46px;
        text-align: right;
        margin-right: 5px;
      }
    }
    .slt-item{
      display: block;
      height: 46px;
      line-height: 46px;
      padding-left: 2px;
    }
  }
  .upload-box{
    display: flex;
    .img{
      margin-right: 12px;
    }
  }
  .btn-box{
    display: flex;
    .btn{
      margin-left: 30px;
    }
  }
}
</style>
